<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="device-list-card">
          <div slot="header" class="clearfix">
            <span>监控设备列表</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="refreshDeviceList"
            >刷新</el-button>
          </div>
          <div v-loading="deviceListLoading" class="device-list">
            <el-table
              :data="deviceList"
              @row-click="handleDeviceSelect"
              highlight-current-row
              :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
              border
            >
              <el-table-column label="设备名称" prop="deviceName" min-width="120" :show-overflow-tooltip="true" />
              <el-table-column label="状态" align="center" width="80">
                <template slot-scope="scope">
                  <el-tag type="success" v-if="scope.row.status == 0">正常</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.status == 1">故障</el-tag>
                  <el-tag type="warning" v-else-if="scope.row.status == 2">维修中</el-tag>
                  <el-tag type="info" v-else-if="scope.row.status == 3">离线</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-card shadow="hover" class="monitor-card">
          <div slot="header" class="clearfix">
            <span>{{ currentDevice ? currentDevice.deviceName : '监控视频' }}</span>
            <div style="float: right;">
              <el-tag v-if="isRecording" type="danger">录制中</el-tag>
              <el-tag v-if="recordingTime">录制时长: {{ formatTime(recordingTime) }}</el-tag>
            </div>
          </div>
          
          <div class="monitor-content">
            <!-- 监控视频/摄像头区域 -->
            <div class="video-container">
              <video ref="videoElement" autoplay></video>
              <canvas ref="canvasElement" style="display: none;"></canvas>
              <div v-if="!currentDevice" class="no-device">
                <i class="el-icon-video-camera"></i>
                <p>请选择一个设备开始监控</p>
              </div>
            </div>
            
            <!-- 控制按钮 -->
            <div class="control-buttons">
              <el-button 
                type="primary" 
                :disabled="!currentDevice || isLoading || isRecording || deviceConnected" 
                @click="startStream"
              >
                <i class="el-icon-video-play"></i> 连接
              </el-button>
              <el-button 
                type="danger" 
                :disabled="!deviceConnected || isLoading" 
                @click="stopStream"
              >
                <i class="el-icon-video-pause"></i> 断开
              </el-button>
              <el-button 
                type="success" 
                :disabled="!deviceConnected || isRecording || isLoading" 
                @click="startRecording"
              >
                <i class="el-icon-video-camera"></i> 开始录制
              </el-button>
              <el-button 
                type="warning" 
                :disabled="!isRecording || isLoading" 
                @click="stopRecording"
              >
                <i class="el-icon-close"></i> 停止录制
              </el-button>
              <el-button 
                type="info" 
                :disabled="!deviceConnected || isLoading" 
                @click="takeSnapshot"
              >
                <i class="el-icon-camera"></i> 截图
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 历史录像列表 -->
    <el-card shadow="hover" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>录像文件列表</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="refreshRecordings"
        >刷新</el-button>
      </div>
      <el-table
        v-loading="recordingsLoading"
        :data="recordings"
        border
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
      >
        <el-table-column label="文件名" prop="fileName" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="设备" prop="deviceName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="录制时间" prop="recordTime" min-width="180" />
        <el-table-column label="文件大小" prop="fileSize" width="100" />
        <el-table-column label="时长" prop="duration" width="100" />
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="isIndexedDBSupported && !scope.row.cannotPlay">可播放</el-tag>
            <el-tag type="danger" v-else>不可播放</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              @click="playRecording(scope.row)"
              :disabled="!isIndexedDBSupported || scope.row.cannotPlay"
            >播放</el-button>
            <el-button 
              size="mini" 
              type="success" 
              @click="downloadRecording(scope.row)"
              :disabled="!isIndexedDBSupported || scope.row.cannotPlay"
            >下载</el-button>
            <el-button size="mini" type="danger" @click="deleteRecording(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!isIndexedDBSupported" class="indexeddb-warning">
        <i class="el-icon-warning"></i>
        <p>您的浏览器不支持视频持久化存储，请使用Chrome、Firefox或Edge浏览器</p>
      </div>
    </el-card>
    
    <!-- 播放录像对话框 -->
    <el-dialog
      title="播放录像"
      :visible.sync="playDialogVisible"
      width="70%"
      :before-close="closePlayDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="video-dialog"
      destroy-on-close
    >
      <div class="video-player-container" v-loading="videoLoading" element-loading-text="视频加载中...">
        <video
          v-if="playingRecording && playingRecording.blobUrl"
          ref="playbackVideo"
          controls
          preload="auto"
          class="video-player"
          :key="playingRecording.fileName"
        >
          <source :src="playingRecording.blobUrl" type="video/webm">
          <p>您的浏览器不支持视频播放。请使用Chrome、Firefox或Edge浏览器。</p>
        </video>
        <div v-else-if="!videoLoading" class="no-video">
          <i class="el-icon-video-camera"></i>
          <p>暂无可播放的视频或视频数据已失效</p>
          <p class="video-help-text" v-if="!isIndexedDBSupported">您的浏览器不支持视频持久化存储</p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePlayDialog">关闭</el-button>
        <el-button v-if="playingRecording" type="primary" @click="downloadRecording(playingRecording)">下载视频</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice } from "@/api/newMonitor/device";
import { Notification } from 'element-ui';

// IndexedDB数据库服务
const dbService = {
  DB_NAME: 'monitorVideoDB',
  DB_VERSION: 1,
  STORE_NAME: 'videos',
  db: null,

  // 打开数据库连接
  async openDB() {
    if (this.db) return this.db;
    
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
      
      request.onerror = (event) => {
        console.error('IndexedDB打开失败:', event);
        reject(new Error('无法打开视频数据库'));
      };
      
      request.onsuccess = (event) => {
        this.db = event.target.result;
        console.log('IndexedDB连接成功');
        resolve(this.db);
      };
      
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains(this.STORE_NAME)) {
          // 创建对象存储，使用视频文件名作为键
          const store = db.createObjectStore(this.STORE_NAME, { keyPath: 'fileName' });
          // 创建索引
          store.createIndex('deviceId', 'deviceId', { unique: false });
          store.createIndex('recordTime', 'recordTime', { unique: false });
          console.log('视频对象存储创建成功');
        }
      };
    });
  },
  
  // 保存视频数据
  async saveVideo(videoData) {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readwrite');
        const store = transaction.objectStore(this.STORE_NAME);
        
        const request = store.put(videoData);
        
        request.onsuccess = () => {
          console.log('视频数据保存成功:', videoData.fileName);
          resolve(true);
        };
        
        request.onerror = (event) => {
          console.error('保存视频数据失败:', event);
          reject(new Error('保存视频失败'));
        };
        
        transaction.oncomplete = () => {
          console.log('视频保存事务完成');
        };
      });
    } catch (error) {
      console.error('保存视频操作失败:', error);
      throw error;
    }
  },
  
  // 获取所有视频元数据(不包含视频Blob数据)
  async getAllVideoMetadata() {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readonly');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.getAll();
        
        request.onsuccess = (event) => {
          // 返回不包含视频Blob的元数据
          const videos = event.target.result.map(video => {
            // 解构，取出blobData之外的所有字段
            const { blobData, ...metadata } = video;
            return metadata;
          });
          resolve(videos);
        };
        
        request.onerror = (event) => {
          console.error('获取视频列表失败:', event);
          reject(new Error('获取视频列表失败'));
        };
      });
    } catch (error) {
      console.error('获取视频列表操作失败:', error);
      throw error;
    }
  },
  
  // 根据文件名获取完整的视频数据
  async getVideoByFileName(fileName) {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readonly');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.get(fileName);
        
        request.onsuccess = (event) => {
          const video = event.target.result;
          if (video) {
            console.log('获取视频成功:', fileName);
            resolve(video);
          } else {
            console.warn('视频不存在:', fileName);
            resolve(null);
          }
        };
        
        request.onerror = (event) => {
          console.error('获取视频失败:', event);
          reject(new Error('获取视频失败'));
        };
      });
    } catch (error) {
      console.error('获取视频操作失败:', error);
      throw error;
    }
  },
  
  // 删除视频
  async deleteVideo(fileName) {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readwrite');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.delete(fileName);
        
        request.onsuccess = () => {
          console.log('视频删除成功:', fileName);
          resolve(true);
        };
        
        request.onerror = (event) => {
          console.error('删除视频失败:', event);
          reject(new Error('删除视频失败'));
        };
      });
    } catch (error) {
      console.error('删除视频操作失败:', error);
      throw error;
    }
  },
  
  // 检查数据库是否支持
  isSupported() {
    return window.indexedDB !== undefined;
  }
};

export default {
  name: "Monitor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控视频表格数据
      videoList: [],
      // 设备列表
      deviceList: [],
      deviceListLoading: false,
      
      // 当前选中的设备
      currentDevice: null,
      
      // 设备连接状态
      deviceConnected: false,
      isLoading: false,
      
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 是否显示播放对话框
      playDialogVisible: false,
      // 预览视频URL
      previewUrl: "",
      // 时间范围
      timeRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        fileName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 播放中的视频对象
      playingRecording: null,
      // 录制状态
      isRecording: false,
      recordingTime: 0,
      recordingTimer: null,
      mediaRecorder: null,
      recordedChunks: [],
      stream: null,
      // 录像文件列表
      recordings: [],
      recordingsLoading: false,
      // 是否支持IndexedDB
      isIndexedDBSupported: false,
      // 播放视频加载状态
      videoLoading: false,
    };
  },
  created() {
    this.getDeviceList();
    // 检查IndexedDB支持
    this.isIndexedDBSupported = dbService.isSupported();
    if (!this.isIndexedDBSupported) {
      this.$message.warning('您的浏览器不支持视频持久化存储，请使用Chrome、Firefox或Edge浏览器');
    }
  },
  mounted() {
    // 如果浏览器不支持MediaRecorder，提示用户
    if (!window.MediaRecorder) {
      this.$message.error('您的浏览器不支持录制功能，请使用Chrome、Firefox或Edge浏览器');
    }
    
    // 加载视频列表
    this.loadRecordings();
    
    // 获取路由参数，如果有设备ID，则自动选择该设备
    const { deviceId } = this.$route.params;
    if (deviceId) {
      this.autoSelectDevice(deviceId);
    }
  },
  beforeDestroy() {
    this.stopStream();
    this.stopRecordingTimer();
  },
  methods: {
    /** 查询设备列表 */
    getDeviceList() {
      this.deviceListLoading = true;
      listDevice({status: '0'}).then(response => {
        this.deviceList = response.rows || [];
        this.deviceListLoading = false;
      }).catch(() => {
        this.deviceListLoading = false;
        this.$message.error('获取设备列表失败');
      });
    },
    
    // 刷新设备列表
    refreshDeviceList() {
      this.getDeviceList();
    },
    
    // 选择设备
    handleDeviceSelect(row) {
      // 如果正在录制，提示用户
      if (this.isRecording) {
        this.$confirm('当前正在录制，切换设备将停止录制，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.stopRecording();
          this.stopStream();
          this.currentDevice = row;
        }).catch(() => {});
      } else {
        // 如果已连接，先断开
        if (this.deviceConnected) {
          this.stopStream();
        }
        this.currentDevice = row;
      }
    },
    
    // 连接摄像头开始流媒体
    async startStream() {
      if (!this.currentDevice) return;
      
      this.isLoading = true;
      
      try {
        // 在实际应用中，这里应该连接到设备的RTSP流
        // 此处使用本地摄像头作为演示
        const constraints = {
          video: {
            width: { ideal: 1920 },
            height: { ideal: 1080 }
          },
          audio: true
        };
        
        // 获取媒体流
        this.stream = await navigator.mediaDevices.getUserMedia(constraints);
        
        // 设置视频源
        const videoElement = this.$refs.videoElement;
        videoElement.srcObject = this.stream;
        
        // 更新状态
        this.deviceConnected = true;
        
        // 如果设置为自动录制，开始录制
        // 取消自动录制的注释即可开启自动录制功能
        // this.startRecording();
        
        Notification.success({
          title: '连接成功',
          message: `已连接到设备: ${this.currentDevice.deviceName}`,
          position: 'bottom-right'
        });
      } catch (error) {
        console.error('获取媒体流失败:', error);
        this.$message.error(`连接摄像头失败: ${error.message}`);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 断开连接
    stopStream() {
      // 如果正在录制，先停止录制
      if (this.isRecording) {
        this.stopRecording();
      }
      
      // 停止所有轨道
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
      }
      
      // 清空视频源
      const videoElement = this.$refs.videoElement;
      if (videoElement && videoElement.srcObject) {
        videoElement.srcObject = null;
      }
      
      // 更新状态
      this.deviceConnected = false;
    },
    
    // 开始录制
    startRecording() {
      if (!this.stream || !window.MediaRecorder) return;
      
      this.isLoading = true;
      
      try {
        // 设置录制选项
        const options = {
          mimeType: 'video/webm;codecs=vp9,opus'
        };
        
        // 创建MediaRecorder实例
        this.mediaRecorder = new MediaRecorder(this.stream, options);
        
        // 录制的数据可用时的处理
        this.recordedChunks = [];
        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.recordedChunks.push(event.data);
          }
        };
        
        // 录制停止时的处理
        this.mediaRecorder.onstop = () => {
          this.saveRecording();
        };
        
        // 开始录制
        this.mediaRecorder.start(1000); // 每秒记录一次数据
        
        // 更新状态
        this.isRecording = true;
        this.recordingTime = 0;
        this.startRecordingTimer();
        
        Notification.info({
          title: '开始录制',
          message: `正在录制设备: ${this.currentDevice.deviceName}`,
          position: 'bottom-right'
        });
      } catch (error) {
        console.error('开始录制失败:', error);
        this.$message.error(`开始录制失败: ${error.message}`);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 停止录制
    stopRecording() {
      if (!this.mediaRecorder || this.mediaRecorder.state === 'inactive') return;
      
      this.isLoading = true;
      
      try {
        // 停止录制
        this.mediaRecorder.stop();
        
        // 停止计时器
        this.stopRecordingTimer();
        
        // 更新状态
        this.isRecording = false;
      } catch (error) {
        console.error('停止录制失败:', error);
        this.$message.error(`停止录制失败: ${error.message}`);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 开始录制计时器
    startRecordingTimer() {
      this.recordingTimer = setInterval(() => {
        this.recordingTime++;
      }, 1000);
    },
    
    // 停止录制计时器
    stopRecordingTimer() {
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
        this.recordingTimer = null;
      }
    },
    
    // 格式化时间
    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      
      return [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0')
      ].join(':');
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 截图
    takeSnapshot() {
      if (!this.deviceConnected) return;
      
      try {
        const videoElement = this.$refs.videoElement;
        const canvasElement = this.$refs.canvasElement;
        
        // 设置canvas大小与视频相同
        canvasElement.width = videoElement.videoWidth;
        canvasElement.height = videoElement.videoHeight;
        
        // 在canvas上绘制当前视频帧
        const ctx = canvasElement.getContext('2d');
        ctx.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
        
        // 转换为图片
        const imageData = canvasElement.toDataURL('image/png');
        
        // 创建文件名
        const now = new Date();
        const formattedDate = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
        const fileName = `${this.currentDevice.deviceName}_${formattedDate}.png`;
        
        // 创建下载链接
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = imageData;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        
        // 延迟后移除链接
        setTimeout(() => {
          document.body.removeChild(a);
        }, 100);
        
        this.$message.success('截图已保存到本地');
      } catch (error) {
        console.error('截图失败:', error);
        this.$message.error(`截图失败: ${error.message}`);
      }
    },
    
    // 自动选择设备
    autoSelectDevice(deviceId) {
      // 等待设备列表加载完成
      if (this.deviceListLoading) {
        setTimeout(() => this.autoSelectDevice(deviceId), 500);
        return;
      }
      
      // 查找设备
      const device = this.deviceList.find(d => d.deviceId == deviceId);
      if (device) {
        // 选择设备
        this.currentDevice = device;
        // 自动连接设备
        this.$nextTick(() => {
          this.startStream();
        });
      } else {
        this.$message.warning('未找到指定的设备，请手动选择设备');
      }
    },
    
    // 加载视频录像列表
    async loadRecordings() {
      this.recordingsLoading = true;
      
      try {
        if (this.isIndexedDBSupported) {
          // 从 IndexedDB 加载视频元数据
          const videos = await dbService.getAllVideoMetadata();
          this.recordings = videos;
          
          if (videos.length > 0) {
            this.$message.success(`成功加载 ${videos.length} 个录像`);
          }
        } else {
          // 从 localStorage 加载视频元数据（不包含视频数据）
          this.loadRecordingsFromStorage();
        }
      } catch (error) {
        console.error('加载录像列表失败:', error);
        this.$message.error('加载录像列表失败: ' + error.message);
      } finally {
        this.recordingsLoading = false;
      }
    },

    // 从localStorage加载录像列表 (兼容旧数据)
    loadRecordingsFromStorage() {
      try {
        const storageData = localStorage.getItem('monitorRecordings');
        if (storageData) {
          this.recordings = JSON.parse(storageData);
          
          // 提示用户这些录像无法播放
          if (this.recordings.length > 0) {
            this.$message.info('检测到旧版本录像，这些录像无法播放，请重新录制');
          }
        }
      } catch (error) {
        console.error('加载本地存储录像列表失败:', error);
        localStorage.removeItem('monitorRecordings');
      }
    },
    
    // 播放录像
    async playRecording(recording) {
      try {
        // 检查是否可以播放
        if (recording.cannotPlay) {
          this.$message.warning('此录像无法播放，请重新录制');
          return;
        }
        
        this.videoLoading = true;
        this.playingRecording = recording;
        this.playDialogVisible = true;
        
        // 等待DOM更新
        await this.$nextTick();
        
        // 判断是否使用IndexedDB
        if (this.isIndexedDBSupported) {
          // 从IndexedDB获取完整视频数据
          const fullVideo = await dbService.getVideoByFileName(recording.fileName);
          
          if (!fullVideo || !fullVideo.blobData) {
            this.$message.error('无法获取视频数据，可能已被删除');
            this.videoLoading = false;
            return;
          }
          
          // 为视频Blob创建URL
          const videoURL = URL.createObjectURL(fullVideo.blobData);
          
          // 更新播放记录添加URL
          this.playingRecording = {
            ...fullVideo,
            blobUrl: videoURL
          };
          
          // 设置视频源并播放
          const videoEl = this.$refs.playbackVideo;
          if (!videoEl) {
            console.error('找不到视频元素');
            this.videoLoading = false;
            return;
          }
          
          // 设置调试事件
          videoEl.addEventListener('canplay', () => {
            console.log('视频可以播放了');
            this.videoLoading = false;
            videoEl.play().catch(err => {
              console.error('播放失败:', err);
              this.$message.error(`播放失败: ${err.message}`);
            });
          }, { once: true });
          
          videoEl.addEventListener('error', (e) => {
            console.error('视频加载错误:', videoEl.error);
            this.$message.error('视频加载失败，请检查浏览器兼容性');
            this.videoLoading = false;
          }, { once: true });
          
          // 设置视频源
          videoEl.src = videoURL;
          videoEl.load();
        } else {
          this.$message.error('您的浏览器不支持视频持久化存储，无法播放录像');
          this.videoLoading = false;
        }
      } catch (error) {
        console.error('播放过程出错:', error);
        this.$message.error(`播放出错: ${error.message}`);
        this.videoLoading = false;
      }
    },
    
    // 关闭播放对话框
    closePlayDialog() {
      try {
        const videoEl = this.$refs.playbackVideo;
        if (videoEl) {
          videoEl.pause();
          videoEl.src = '';
          videoEl.removeAttribute('src');
          videoEl.load();
        }
        
        // 释放Blob URL
        if (this.playingRecording && this.playingRecording.blobUrl) {
          URL.revokeObjectURL(this.playingRecording.blobUrl);
        }
        
        this.playDialogVisible = false;
        this.playingRecording = null;
        this.videoLoading = false;
      } catch (error) {
        console.error('关闭播放器失败:', error);
      }
    },
    
    // 刷新录像列表
    refreshRecordings() {
      this.loadRecordings();
    },
    
    // 下载录像
    async downloadRecording(recording) {
      try {
        if (this.isIndexedDBSupported) {
          // 从IndexedDB获取完整视频数据
          const fullVideo = await dbService.getVideoByFileName(recording.fileName);
          
          if (!fullVideo || !fullVideo.blobData) {
            this.$message.error('无法获取视频数据，可能已被删除');
            return;
          }
          
          // 创建临时URL
          const url = URL.createObjectURL(fullVideo.blobData);
          
          // 下载文件
          const a = document.createElement('a');
          a.style.display = 'none';
          a.href = url;
          a.download = recording.fileName;
          document.body.appendChild(a);
          a.click();
          
          // 清理
          setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
          }, 100);
          
          this.$message.success('开始下载录像');
        } else {
          this.$message.warning('无法下载录像，视频数据不可用');
        }
      } catch (error) {
        console.error('下载录像失败:', error);
        this.$message.error(`下载录像失败: ${error.message}`);
      }
    },
    
    // 删除录像
    deleteRecording(recording) {
      this.$confirm('确定要删除该录像吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 从列表中移除
          const index = this.recordings.findIndex(r => r.fileName === recording.fileName);
          if (index !== -1) {
            this.recordings.splice(index, 1);
            
            // 从IndexedDB中删除
            if (this.isIndexedDBSupported) {
              await dbService.deleteVideo(recording.fileName);
            }
            
            this.$message.success('录像已删除');
          }
        } catch (error) {
          console.error('删除录像出错:', error);
          this.$message.error(`删除录像失败: ${error.message}`);
        }
      }).catch(() => {});
    },
    
    // 保存录制的视频
    async saveRecording() {
      if (this.recordedChunks.length === 0) return;
      
      try {
        // 创建Blob对象
        const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
        
        // 创建文件名 (使用时间戳保证唯一性)
        const now = new Date();
        const formattedDate = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
        const fileName = `${this.currentDevice.deviceName}_${formattedDate}.webm`;
        
        // 创建临时URL用于下载
        const url = URL.createObjectURL(blob);
        
        // 自动下载视频文件
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        
        // 延迟后移除下载链接
        setTimeout(() => {
          document.body.removeChild(a);
          URL.revokeObjectURL(url); // 释放临时URL
        }, 100);
        
        // 创建要保存的视频数据对象
        const videoData = {
          fileName: fileName,
          deviceName: this.currentDevice.deviceName,
          deviceId: this.currentDevice.deviceId,
          recordTime: now.toLocaleString(),
          fileSize: this.formatFileSize(blob.size),
          duration: this.formatTime(this.recordingTime),
          blobData: blob, // 存储Blob数据到IndexedDB
          mimeType: 'video/webm'
        };
        
        if (this.isIndexedDBSupported) {
          // 保存到IndexedDB
          await dbService.saveVideo(videoData);
          
          // 添加到录像列表 (不包含blob数据，避免页面卡顿)
          const { blobData, ...metadata } = videoData;
          this.recordings.unshift(metadata);
          
          Notification.success({
            title: '录制完成',
            message: `文件已保存: ${fileName}`,
            position: 'bottom-right'
          });
        } else {
          // 如果不支持IndexedDB，显示提示
          this.$message.warning('您的浏览器不支持视频持久化存储，视频将只能下载到本地');
          // 添加到录像列表，但标记为不可播放
          this.recordings.unshift({
            ...videoData,
            cannotPlay: true
          });
          localStorage.setItem('monitorRecordings', JSON.stringify(this.recordings));
        }
      } catch (error) {
        console.error('保存录制失败:', error);
        this.$message.error(`保存录制失败: ${error.message}`);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.device-list-card {
  height: 600px;
}

.device-list {
  height: 530px;
  overflow-y: auto;
}

.monitor-card {
  height: auto;
  min-height: 600px;
}

.monitor-content {
  display: flex;
  flex-direction: column;
}

.video-container {
  height: 400px;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  margin-bottom: 20px;
  overflow: hidden;
}

.video-container video {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
}

.no-device {
  text-align: center;
  color: #909399;
}

.no-device i {
  font-size: 64px;
  margin-bottom: 16px;
}

.control-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
  position: relative;
  z-index: 10;
  padding-bottom: 10px;
}

/* IndexedDB警告样式 */
.indexeddb-warning {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff6f6;
  border-left: 3px solid #f56c6c;
  display: flex;
  align-items: center;
  
  i {
    font-size: 18px;
    color: #f56c6c;
    margin-right: 10px;
  }
  
  p {
    margin: 0;
    color: #f56c6c;
  }
}

/* 修正tag间距 */
.el-tag {
  margin-right: 8px;
}

/* 表格中的按钮间距 */
.el-button+.el-button {
  margin-left: 5px;
}

/* 视频播放对话框 */
.video-dialog {
  .video-player-container {
    background: #000;
    padding: 20px;
    border-radius: 4px;
    min-height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .video-player {
    width: 100%;
    max-height: 70vh;
    object-fit: contain;
  }

  .no-video {
    text-align: center;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
    }

    p {
      margin: 0 0 8px;
      font-size: 14px;
    }

    .video-help-text {
      font-size: 12px;
      color: #c0c4cc;
    }
  }
}

/* 当屏幕较小时调整布局 */
@media screen and (max-width: 768px) {
  .video-container {
    height: 300px;
  }
  
  .control-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .control-buttons .el-button {
    width: 100%;
    margin-bottom: 5px;
  }
}

/* 优化视频控件样式 */
video::-webkit-media-controls {
  background-color: rgba(0, 0, 0, 0.5);
}

video::-webkit-media-controls-panel {
  padding: 0 10px;
}

video::-webkit-media-controls-play-button {
  margin: 0 5px;
}

video::-webkit-media-controls-timeline {
  margin: 0 10px;
}
</style>
